package com.hontech.bvapp2.device

import serial.codec.CodecType
import serial.encodeU8
import serial.usb.xorSum


object Address {

    const val IPC = 0
    const val IPC_NAME = "工控机"

    const val WEIGHT = 1
    const val WEIGHT_NAME = "称重控制板"

    const val CARGO1 = 2
    const val CARGO1_NAME = "货架1控制板"

    const val CARGO2 = 3
    const val CARGO2_NAME = "货架2控制板"

    const val HEAT = 4
    const val HEAT_NAME = "加热控制板"

    const val DOOR = 5
    const val DOOR_NAME = "门控制板"

    const val DROP = 6
    const val DROP_NAME = "切膜落杯控制板"

    const val MY = IPC

    fun getName(address: Int): String {
        when (address) {
            CARGO1 -> return CARGO1_NAME
            CARGO2 -> return CARGO2_NAME
            HEAT -> return HEAT_NAME
            DOOR -> return DOOR_NAME
            DROP -> return DROP_NAME
        }
        throw IllegalStateException("未知地址:$address")
    }

    fun getAddress(name: String): Int {
        when (name) {
            CARGO1_NAME -> return CARGO1
            CARGO2_NAME -> return CARGO2
            HEAT_NAME -> return HEAT
            DOOR_NAME -> return DOOR
            DROP_NAME -> return DROP
        }
        throw IllegalStateException("未知控制板:$name")
    }
}

object Ty {

    const val SIMPLE_REQ = 0
    const val SIMPLE_RES = 1

    const val REQ = 2
    const val REQ_ACK = 3

    const val RES = 4
    const val RES_ACK = 5

    const val NOTIFY = 6

    const val PING = 7
    const val PONG = 8

    const val CONNECT = 9
    const val CONNECT_ACK = 0x0A

    const val POLL = 0x0B
    const val POLL_ACK = 0x0C

    const val LOG = 0x0D
}

object Proto {

    private const val HEAD0 = 0xE1
    private const val HEAD1 = 0x1E
    private const val END = 0xEF
    private const val MIN_LEN = 9
    const val MIN_CMD_LEN = 10
    const val MIN_RES_LEN = 11

    fun makeEmpty(ty: Int, seq: Int, src: Int, dst: Int): ByteArray {
        val buf = byteArrayOf(
            HEAD0.toByte(),
            HEAD1.toByte(),
            MIN_LEN.toByte(),
            ty.toByte(),
            seq.toByte(),
            src.toByte(),
            dst.toByte(),
            0,
            END.toByte()
        )
        val s = xorSum(buf, 3, 4)
        buf[7] = s.toByte()
        return buf
    }

    fun make(ty: Int, seq: Int, src: Int, dst: Int, vararg args: CodecType): ByteArray {
        var len = MIN_LEN
        for (arg in args) {
            len += arg.size()
        }
        val buf = ByteArray(len)

        encodeU8(buf, 0, HEAD0)
        encodeU8(buf, 1, HEAD1)
        encodeU8(buf, 2, len)
        encodeU8(buf, 3, ty)
        encodeU8(buf, 4, seq)
        encodeU8(buf, 5, src)
        encodeU8(buf, 6, dst)
        var index = 7
        for (arg in args) {
            arg.encode(buf, index)
            index += arg.size()
        }
        val s = xorSum(buf, 3, len - 5)
        encodeU8(buf, index, s)
        encodeU8(buf, index + 1, END)
        return buf
    }

}









